<!-- 床位管理页 -->
<template>
  <!-- 面包屑 -->
  <div style="margin: 20px;">
    <el-breadcrumb separator="/" style="line-height:35px">
      <el-breadcrumb-item><span style="color: #7A7A7A;">服务管理</span></el-breadcrumb-item>
      <el-breadcrumb-item><span style="color: #7A7A7A;">床位管理</span></el-breadcrumb-item>
      <el-breadcrumb-item><span style="color: #0468FF;font-weight: bold">床位管理</span></el-breadcrumb-item>
    </el-breadcrumb>
  </div>
  <!-- 搜索栏 -->
  <el-card style="margin: 20px;height: 120px;border: 0" shadow="never">
    <el-form>
      <el-row>
        <el-col :span="12">
          <el-form-item label="老人姓名" style="width: 400px;">
            <el-input placeholder="请输入老人姓名" v-model="searchForm.name"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="房间号" style="width: 400px;">
            <el-select v-model="searchForm.roomNumber"
                       @change="changeRoomNumber"
                       placeholder="请选择房间号">
              <el-option v-for="item in roomList" :label="item.number" :value="item.number"></el-option>
            </el-select>
          </el-form-item>
        </el-col>

      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="床位状态" style="width: 400px;">
            <el-select v-model="searchForm.status"
                       @change="loadBedInfo"
                       placeholder="请选择床位状态">
              <el-option label="全部" value=""></el-option>
              <el-option label="空闲" value="空闲"></el-option>
              <el-option label="已占用" value="已占用"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item>
            <el-button @click="resetSearch">重置</el-button>
            <el-button type="primary" @click="loadBedInfo">查询</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </el-card>

  <!-- 床位卡片列表 -->
  <el-card style="margin: 20px 20px 1px;
                  border: 0;border-bottom-left-radius: 0;
                  border-bottom-right-radius: 0"
           shadow="never">
    <el-row :gutter="10">
      <el-col :span="4"><span style="font-weight: bold">康复一区（{{ patientTotal }}人）</span></el-col>
      <el-col :span="4"><span style="font-size: 14px">本房间全部床位（{{ thisRoomBedTotal }}）</span></el-col>
      <el-col :span="3"><span style="font-size: 14px">已占床位（{{ occupyTotal }}）</span></el-col>
      <el-col :span="4"><span style="font-size: 14px">空余床位（{{ notOccupyTotal }}）</span></el-col>
    </el-row>
  </el-card>
  <el-card v-loading="loading" style="border: 0;margin: 0 20px;border-top-right-radius: 0;border-top-left-radius: 0;"
           shadow="never">
    <el-card class="infoCard" v-for="(item,i) in dataList">
      <!-- 非空床 -->
      <div class="circle" v-if="item.name!=null"><span v-if="item.number < 10">0</span>{{ item.number }}</div>
      <div v-if="item.name!=null">
        <div style="position: absolute;left: 90px;top: 20px">
          <div style="font-weight: bold">
            <span style="font-size: 16px;">{{ item.name }}&nbsp;&nbsp;</span>
            <span style="font-size: 12px;color: #555;line-height: 35px">
              {{ item.gender }}&nbsp;&nbsp;{{ item.age }}岁</span>
          </div>
          <div style="font-size: 12px;color: #555">{{ item.security }}</div>
        </div>
        <div style="position: absolute;bottom: 70px;font-size: 12px;line-height: 25px;color: #555">
          <div>入院时间：{{ item.checkInTime }}</div>
          <div>责任护士：{{ item.doctorId }}</div>
          <div>房间：{{ item.roomNumber }}</div>
        </div>
      </div>
      <!-- 数据卡片左下角的菜单 -->
      <el-dropdown v-if="item.name!=null" style="position: absolute;bottom: 15px;right: 10px;">
        <span class="el-dropdown-link">
          <i style="font-size: 18px;color: #000;" class="iconfont icon-menu"></i>
        </span>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item @click="setEmpty(item)">
              <div style="color: #000;padding:5px 0;">床位置空</div>
            </el-dropdown-item>
            <el-dropdown-item @click="openAddDialog('转房',item)">
              <div style="color: #000;padding:5px 0;">转房</div>
            </el-dropdown-item>
            <el-dropdown-item @click="openAddDialog('转床',item)">
              <div style="color: #000;padding:5px 0;">转床</div>
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>

      <!-- 空床 -->
      <div class="circle" v-if="item.name==null" style="color: #7f7f7f;background-color: #fff">
        <span v-if="i + 1 < 10">0</span>{{ i + 1 }}
      </div>
      <div v-if="item.name==null">
        <div style="color: #7f7f7f;font-size: 18px;font-weight: bold;margin-top: 15px;margin-left: 85px;">空床</div>
        <div style="position: relative;left: 17px;top:30px">
          <img src="/imgs/emptyBed.png" alt="" width="70">
        </div>
        <el-button @click="openDialog(item.bedId,item.roomId)"
                   style="border:1px solid #0468FF;width: 100px;height: 32px;position: relative;left: 50px;top: 35px;">
          <el-icon color="#0468ff" style="font-size: 16px;font-weight: bold">
            <Plus/>
          </el-icon>
          <span style="color: #0468FF;font-weight: 400">&nbsp;床位分配</span>
        </el-button>
      </div>
    </el-card>
  </el-card>

  <!-- 床位分配弹窗 -->
  <el-dialog title="选择老人" v-model="dialogVisible"
             :before-close="handleClose"
             top="8vh"
             style="">
    <el-table :data="currentTableData" height="550px"
              :row-style="{'height':'50px'}"
              :cell-style="{'color':'#000'}"
              :header-cell-style="{
                'background-color': '#f2f2f2',
                'color': '#000',
                'height':'50px'
              }">
      <el-table-column prop="id" label="档案编号" align="center" width="200"/>
      <el-table-column prop="name" label="姓名" align="center"/>
      <el-table-column prop="gender" label="性别" align="center"/>
      <el-table-column prop="age" label="年龄" align="center"/>
      <el-table-column prop="checkInTime" label="入院时间" align="center" width="200"/>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button link type="primary" @click="select(scope.row)">选择</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="dialogData.length"
        style="margin-top: 20px;margin-left: 5px;"
    />
  </el-dialog>

  <!-- 转床/转房 弹窗 -->
  <el-dialog :title="turnTitle"
             :before-close="handleClose2"
             v-model="addDialogVisible"
             top="10vh" style="width: 790px;">
    <el-divider content-position="left">老人信息</el-divider>
    <el-form style="padding: 0 40px;" label-width="80" label-position="left">
      <el-row :gutter="58">
        <el-col :span="12">
          <el-form-item label="档案编码">
            <el-input disabled v-model="addForm.id" placeholder="点击选择老人档案"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="老人姓名">
            <el-input v-model="addForm.name" disabled placeholder="点击选择老人后自动填入"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="58">
        <el-col :span="12">
          <el-form-item label="入院时间">
            <el-input v-model="addForm.checkInTime" disabled placeholder="点击选择老人后自动填入"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-divider content-position="left">原床位</el-divider>
    <el-form style="padding: 0 40px;" label-width="80" label-position="left">
      <el-row :gutter="58">
        <el-col :span="12">
          <el-form-item label="楼层">
            <el-input v-model="addForm.floorNumber" disabled placeholder="请输入"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="房间号">
            <el-input v-model="addForm.roomNumber" disabled placeholder="请输入"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="58">
        <el-col :span="12">
          <el-form-item label="床位号">
            <el-input v-model="addForm.originBedNumber" disabled placeholder="请输入"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="床位价格">
            <el-input v-model="addForm.originBedPrice" disabled placeholder="请输入"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-divider v-if="turnTitle=='转床'" content-position="left">更换床位</el-divider>
    <el-divider v-if="turnTitle=='转房'" content-position="left">更换房间</el-divider>
    <el-form style="padding: 0 40px;" label-width="80" label-position="left">
      <el-row :gutter="58">
        <el-col :span="12">
          <el-form-item label="房间号">
            <el-select class="room-select" v-if="turnTitle=='转房'" v-model="addForm.newRoomNumber"
                       placeholder="请选择房间号">
              <el-option v-for="item in roomList"
                         @click="addForm.newFloor=item.floorNumber;addForm.newBedNumber=''"
                         :label="item.number"
                         :value="item.number"></el-option>
            </el-select>
            <el-input v-if="turnTitle=='转床'"
                      class="room-select"
                      disabled
                      v-model="addForm.roomNumber"
                      placeholder=""></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="床位号">
            <el-select v-model="addForm.newBedNumber" placeholder="请选择床位" @click="getBedList(turnTitle)">
              <el-option v-for="item in bedList"
                         :label="item.number"
                         :value="item.number"
                         @click="addForm.newBedPrice=item.price"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="58">
        <el-col :span="12">
          <el-form-item label="楼层">
            <el-input v-if="turnTitle=='转房'" v-model="addForm.newFloor" disabled placeholder="请输入"></el-input>
            <el-input v-if="turnTitle=='转床'" v-model="addForm.floorNumber" disabled placeholder="请输入"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="床位价格">
            <el-input v-model="addForm.newBedPrice" disabled placeholder="请输入"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label-position="left" label="更换原因">
        <el-input style="width: 600px;"
                  v-model="addForm.reason"
                  placeholder="请输入原因"
                  maxlength="20"
                  type="textarea"
                  :rows="3"
                  show-word-limit></el-input>
      </el-form-item>
    </el-form>

    <span slot="footer" class="dialog-footer">
      <el-button @click="handleClose2">取消</el-button>
      <el-button type="primary" @click="saveTurnRoom">保存</el-button>
    </span>
  </el-dialog>
</template>

<script setup>
import {onMounted, ref} from "vue";
import axios from "axios";
import qs from "qs";
import {ElMessage} from "element-plus";

const searchForm = ref({name: '', roomNumber: '1101', status: ''})

//重置搜索栏
const resetSearch = () => {
  searchForm.value = {name: '', roomNumber: '1101', status: ''}
  loadBedInfo()
}
//数据列表
const dataList = ref([])
//加载数据
const loadBedInfo = () => {
  dataList.value = []
  let data = qs.stringify(searchForm.value)
  axios.get(BASE_URL + '/v1/bed/selectBedCard?' + data)
      .then((response) => {
        if (response.data.state == 2000) {
          dataList.value = response.data.data
        } else {
          ElMessage.error(response.data.message)
        }
      })
}
onMounted(() => {
  changeRoomNumber()
  loadDialogData()
})

//控制弹窗显示
const dialogVisible = ref(false)
//被选中的床位
const selectedBed = ref({bedId: '', roomId: ''})
//打开弹窗
const openDialog = (bedId, roomId) => {
  dialogData.value = []
  loadDialogData()
  dialogVisible.value = true

  selectedBed.value = {bedId: bedId, roomId: roomId}
}
//弹窗表格数据
const dialogData = ref([])
const currentTableData = ref([]) // 当前页显示的数据
const currentPage = ref(1)      // 当前页码
const pageSize = ref(10)        // 每页条数
//加载表格数据
const loadDialogData = () => {
  axios.get(BASE_URL + '/v1/patient/selectNoBedPatient')
      .then((response) => {
        if (response.data.state == 2000) {
          dialogData.value = response.data.data
          updateCurrentData()
        } else {
          ElMessage.error(response.data.message)
        }
      })
}

// 获取数据（示例）
const fetchData = async () => {
  // 这里替换为你的API请求
  // dataTable.value = await api.getData();
  // updateCurrentData();
}

// 更新当前页数据
const updateCurrentData = () => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  currentTableData.value = dialogData.value.slice(start, end)
}

// 每页条数变化
const handleSizeChange = (val) => {
  pageSize.value = val
  updateCurrentData()
}

// 页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  updateCurrentData()
}

// 生命周期钩子
onMounted(() => {
  fetchData()
})

//处理弹窗关闭
const handleClose = () => {
  dialogData.value = [];
  dialogVisible.value = false;
}

const loading = ref(false)
//弹窗中的选择操作
const select = (item) => {
  let data = qs.stringify({id: item.id, bedId: selectedBed.value.bedId, roomId: selectedBed.value.roomId})
  axios.post(BASE_URL + '/v1/bed/allocation', data)
      .then((response) => {
        if (response.data.state == 2000) {
          ElMessage.success('操作成功!')
        } else {
          ElMessage.error(response.data.message)
        }
      })
  handleClose()
  loading.value = true
  setTimeout(() => {
    loadBedInfo()
    loading.value = false
  }, 100)

}

//将床位置空
const setEmpty = (item) => {
  if (!confirm('是否继续操作该置空床位？')) {
    return
  }
  let data = qs.stringify({id: item.id, bedId: item.bedId})
  axios.post(BASE_URL + '/v1/bed/toEmpty', data)
      .then((response) => {
        if (response.data.state == 2000) {
          ElMessage.success('操作成功！')
        } else {
          ElMessage.error(response.data.message)
        }
      })
  loading.value = true
  setTimeout(() => {
    loadBedInfo()
    loading.value = false
  }, 100)
}

//转床和转房弹窗相关
const turnTitle = ref('转床')
const addDialogVisible = ref(false)
const addForm = ref({
  id: '',
  name: '',
  checkInTime: '',
  floorNumber: '',
  roomNumber: '',
  originBedNumber: '',
  originBedPrice: '',
  newRoomNumber: '',
  newFloor: '',
  newBedNumber: '',
  newBedPrice: '',
  reason: ''
})
const openAddDialog = (title, item) => {
  addDialogVisible.value = true
  turnTitle.value = title
  addForm.value.id = item.id
  addForm.value.name = item.name
  addForm.value.checkInTime = item.checkInTime
  addForm.value.floorNumber = item.floorNumber
  addForm.value.roomNumber = item.roomNumber
  addForm.value.originBedNumber = item.number
  addForm.value.originBedPrice = item.price
}
const handleClose2 = () => {
  addDialogVisible.value = false
  addForm.value = {
    id: '',
    name: '',
    checkInTime: '',
    floorNumber: '',
    roomNumber: '',
    originBedNumber: '',
    originBedPrice: '',
    newRoomNumber: '',
    newFloor: '',
    newBedNumber: '',
    newBedPrice: '',
    reason: ''
  }
  bedList.value = []
}

//获取可选房间列表
const roomList = ref([])
const getRoomList = () => {
  axios.get(BASE_URL + '/v1/room/select?')
      .then((response) => {
        if (response.data.state == 2000) {
          roomList.value = response.data.data
        } else {
          ElMessage.error(response.data.message)
        }
      })
}
onMounted(() => {
  getRoomList()
})

//获取可选床位列表
const bedList = ref([])
const getBedList = (title) => {
  let data
  if (title == '转房') {
    if (addForm.value.newRoomNumber == '') {
      ElMessage.warning('请先选择房间号')
      return
    }
    data = qs.stringify({status: '空闲', roomNumber: addForm.value.newRoomNumber});
  }
  if (title == '转床') {
    data = qs.stringify({status: '空闲', roomNumber: addForm.value.roomNumber})
  }
  axios.get(BASE_URL + '/v1/bed/selectEmptyBedList?' + data)
      .then((response) => {
        if (response.data.state == 2000) {
          bedList.value = response.data.data
        } else {
          ElMessage.error(response.data.message)
        }
      })
}

//转房/转床弹窗中的保存
const saveTurnRoom = () => {
  let data;
  if (turnTitle.value == '转房') {
    //封装请求参数
    data = qs.stringify({
      id: addForm.value.id,
      bedNumber: addForm.value.originBedNumber,
      roomNumber: addForm.value.roomNumber,
      newBedNumber: addForm.value.newBedNumber,
      newRoomNumber: addForm.value.newRoomNumber,
      reason: addForm.value.reason
    })
    if (addForm.value.newRoomNumber == '' || addForm.value.newBedNumber == '') {
      ElMessage.error('房间号和床号不能为空！')
      return
    }
    axios.post(BASE_URL + '/v1/turnRoom/add', data)
        .then((response) => {
          if (response.data.state == 2000) {

          } else {
            ElMessage.error(response.data.message)
          }
        })
  }
  if (turnTitle.value == '转床') {
    //封装请求参数
    data = qs.stringify({
      id: addForm.value.id,
      bedNumber: addForm.value.originBedNumber,
      roomNumber: addForm.value.roomNumber,
      newBedNumber: addForm.value.newBedNumber,
      newRoomNumber: addForm.value.roomNumber,
      reason: addForm.value.reason
    })
    if (addForm.value.newBedNumber == '') {
      ElMessage.error('床号不能为空！')
      return
    }
    axios.post(BASE_URL + '/v1/turnBed/add', data)
        .then((response) => {
          if (response.data.state == 2000) {

          } else {
            ElMessage.error(response.data.message)
          }
        })
  }


  axios.post(BASE_URL + '/v1/bed/turnRoom', data)
      .then((response) => {
        if (response.data.state == 2000) {
          ElMessage.success('保存成功！')
        } else {
          ElMessage.error(response.data.message)
        }
      })
  //关闭弹窗
  handleClose2()
  //重新加载卡片列表
  loading.value = true
  setTimeout(() => {
    loadBedInfo()
    loading.value = false
  }, 100)
}


//获取统计信息
//总人数
const patientTotal = ref(0)
const getTotal = () => {
  axios.get(BASE_URL + '/v1/patient/patientTotal')
      .then((response) => {
        if (response.data.state == 2000) {
          patientTotal.value = response.data.data
        } else {
          ElMessage.error('获取失败！')
        }
      })
}
onMounted(() => {
  getTotal()
})
//当前房间的全部床位
const thisRoomBedTotal = ref(0)
const getBedTotalByRoom = () => {
  thisRoomBedTotal.value = 0
  let data = qs.stringify({roomNumber: searchForm.value.roomNumber})
  axios.get(BASE_URL + '/v1/bed/getBedTotalByRoom?' + data)
      .then((response) => {
        if (response.data.state == 2000) {
          thisRoomBedTotal.value = response.data.data
        } else {
          ElMessage.error('获取失败！')
        }
      })
}
//已占床位
const occupyTotal = ref(0)
const getOccupyTotal = () => {
  occupyTotal.value = 0
  for (let i = 0; i < dataList.value.length; i++) {
    if (dataList.value[i].status == '已占用') {
      occupyTotal.value = occupyTotal.value + 1
    }
  }
}
//空闲床位
const notOccupyTotal = ref(0)
const getNotOccupyTotal = () => {
  notOccupyTotal.value = thisRoomBedTotal.value - occupyTotal.value
}
//房号改变时触发
const changeRoomNumber = () => {
  loadBedInfo()
  loading.value = true
  getBedTotalByRoom()
  setTimeout(() => {
    getOccupyTotal()
  }, 100)
  setTimeout(() => {
    getNotOccupyTotal()
    loading.value = false
  }, 100)

}
</script>

<style scoped>
.infoCard {
  width: 22%;
  height: 230px;
  display: inline-block;
  margin: 10px 15px;
  position: relative;
}

.circle {
  width: 50px;
  height: 50px;
  background-color: #e7f5ff;
  border-radius: 50%;
  text-align: center;
  line-height: 50px;
  color: #0468FF;
  float: left;
  font-size: 18px;
  border: 1px solid;
}

.el-dialog .el-input {
  width: 230px;
}

</style>